package com.tskj.mh.getordertime.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tskj.mh.getordertime.dao.redis.RedisUtil;
import com.tskj.mh.getordertime.utility.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class GetOrderTimeService {

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 检查学生在当天的指定食堂的指定餐段中有没有下过订单
     * 同一天，同一食堂，同一餐段，只能有一个订单
     * @param userId
     * @param resId
     * @param timeTypeId
     * @return
     */
    private Boolean checkOrder(String userId, String resId, String timeTypeId) {
        String today = Tools.today();
        return true;
    }

    public JSONArray getTimeList(String resId, String timeTypeId) {
        String time_now = Tools.getNowTime();
        JSONArray list = new JSONArray();
        Map<Object, Object> map = redisUtil.hmget(Tools.today());
        if (map != null) {
            HashMap<Object, Object> allTimeList = (HashMap<Object, Object>) map;
            Set<Object> keys = allTimeList.keySet();
            JSONObject time;
//            System.out.println(time_now);
            for (Object key : keys) {
                JSONObject obj = JSONObject.parseObject(allTimeList.get(key).toString());
                if (obj.getString("resid").equals(resId) && obj.getString("timetypeid").equals(timeTypeId)) {
//                    System.out.println(Tools.addTime(obj.getString("begin"), -30));
                    if (Tools.isBefore(Tools.addTime(obj.getString("begin"), -30), time_now)) {
//                        System.out.println("开始时间的前30分钟小于当前时间");
                        continue;
                    }

                    time = new JSONObject();
                    time.put("id", obj.getString("id"));
                    time.put("timeTitle", String.format("%s - %s", obj.getString("begin").substring(0, 5), obj.getString("end").substring(0, 5)));
                    time.put("timeCount", obj.getIntValue("used"));
                    list.add(time);
                }
            }
        }
        return Tools.jsonArraySort(list, "timeTitle", false);
    }

    public void insertTimeList(String timeId) {
        String today = Tools.today();
        String key = today + "_" + timeId;
        long size = redisUtil.lGetListSize(key);
        for (long j = 0; j < size; j++) {
            redisUtil.leftPop(key);
        }
        for (int i = 0; i < 200; i++) {
            redisUtil.lSet(key, i);
        }
    }

}
